
package com.shop.cloud.mall.api.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.mall.api.mapper.UserWithdrawRecordMapper;
import com.shop.cloud.mall.api.service.DistributionUserService;
import com.shop.cloud.mall.api.service.UserBalanceRecordService;
import com.shop.cloud.mall.api.service.UserBalanceService;
import com.shop.cloud.mall.api.service.UserWithdrawRecordService;
import com.shop.cloud.mall.common.constant.MallConstants;
import com.shop.cloud.mall.common.entity.UserBalanceRecord;
import com.shop.cloud.mall.common.entity.UserWithdrawRecord;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.boot.autoconfigure.klock.model.LockTimeoutStrategy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户提现记录
 *
 * @author
 * @date 2021-05-10 14:20:02
 */
@Service
@AllArgsConstructor
public class UserWithdrawRecordServiceImpl extends ServiceImpl<UserWithdrawRecordMapper, UserWithdrawRecord> implements UserWithdrawRecordService {

    private final DistributionUserService distributionUserService;
    private final UserBalanceRecordService userBalanceRecordService;
    private final UserBalanceService userBalanceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Klock(name = "commissiontoUserBalance", keys = {"#userWithdrawRecord.getUserId()"}, lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
    public void commissiontoUserBalance(UserWithdrawRecord userWithdrawRecord) {
        //更新用户已提现佣金额度
        distributionUserService.updateCommissionWithdrawal(userWithdrawRecord.getUserId(),userWithdrawRecord.getApplyAmount());
        //新增提现记录
        baseMapper.insert(userWithdrawRecord);
        //更新用户余额
        userBalanceService.updateTotalAmount(userWithdrawRecord.getUserId(), userWithdrawRecord.getApplyAmount());
        //新增余额记录
        UserBalanceRecord userBalanceRecord = new UserBalanceRecord();
        userBalanceRecord.setUserId(userWithdrawRecord.getUserId());
        userBalanceRecord.setIsPay(CommonConstants.YES);
        userBalanceRecord.setType(MallConstants.USER_BALANCE_RECORD_TYPE_2);
        userBalanceRecord.setRelationId(userWithdrawRecord.getId());
        userBalanceRecord.setAmount(userWithdrawRecord.getApplyAmount());
        userBalanceRecordService.save(userBalanceRecord);
    }
}
